import Vue from 'vue'
import VueRouter from 'vue-router'
import { getItem } from '@/utils/storage.js'
import store from '@/store/'
import { getToken } from '@/api/user.js'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout'),
    children: [
      {
        path: '',
        component: () => import('@/views/home')
      }, {
        path: '/video',
        component: () => import('@/views/video')
      },
      {
        path: '/qa',
        component: () => import('@/views/qa')
      },
      {
        path: '/profile',
        component: () => import('@/views/profile')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login')
  },
  {
    path: '/search',
    component: () => import('@/views/search')
  },
  {
    path: '/article/:articleId',
    component: () => import('@/views/article'),
    // 将路由动态参数映射到组件的 props 中，更推荐这种做法
    props: true
  },
  {
    path: '/user',
    component: () => import('@/views/user')
  }
]

const router = new VueRouter({
  routes
})
// 路由钩子
// 约定过期时间
const tokenTimeout = 5 * 60 * 1000
router.beforeEach(async (to, from, next) => {
  const loginDate = getItem('TOKENDATE')
  const currentDate = Date.now()
  console.log(currentDate, loginDate)
  if (store.state.user && currentDate - loginDate > tokenTimeout) {
    const res = await getToken()
    console.log(res.data.data.token)
    store.commit('setUser', {
      ...store.state.user,
      token: res.data.data.token
    })
  }
  next()
})
export default router
